<!-- =============================== -->
<!-- =============================== -->
<!-- ===========查蛋界面============== -->
<!-- =============================== -->
<!-- =============================== -->
<template>
	<view>
		<view class="circle">
			<!-- <view class="houseId row-center">
				 {{show_nfcId ? '鸽舍号：'+ show_nfcId : '鸽舍号'}}
			</view> -->
			<proportion :leftValue="stayCount" :rightValue="whipCount"></proportion>
			<view class="ul" v-if="cageStatu.length">
				<view class="box" v-for="(item,index) in cageStatu" :key="index">
					<view class="li">
						<!-- 时间区域 -->
						<view class="time_list">
							<span v-for="(ite,index1) in layTime.length > 0 ? layTime[index].time : []"
								:key="index1" :class="ite.statu">
								{{formatting(ite.egg_time)}}
								<template v-if="ite.statu === 'out'">淘汰</template>
								<template v-if="ite.statu === 'line-bottom'">留</template>
								<template v-if="ite.statu === 'single'">单</template>
								<template v-if="ite.statu === 'spermatozonia'">光</template>
								<template v-if="ite.statu === 'breakage'">破损</template>
								<template v-if="ite.statu === 'abandon'">弃仔</template>
								<template v-if="ite.statu === 'discard'">弃孵</template>
								<template v-if="ite.statu === 'death_old=1'">种鸽死亡1</template>
								<template v-if="ite.statu === 'death_old=2'">种鸽死亡2</template>
								<template v-if="ite.statu === 'death_young=1'">雏鸽死亡1</template>
								<template v-if="ite.statu === 'death_young=2'">雏鸽死亡2</template>
								<template v-if="ite.statu === 'death_young=3'">雏鸽死亡3</template>
								<template v-if="ite.statu === 'death_young=4'">雏鸽死亡4</template>
							</span>
						</view>
						
						<!-- 鸽笼信息 -->
						<view class="cage_info" @tap="submit(item)" @longpress="longPress(item)"
							@touchend="tounchend" :class="setStyle(item.statu) ? 'ycd' : 'other'">
							<view class="cage_number">{{item.cage_id}}</view>
							<view class="cage_statu">{{item.statu}}</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 顶部提示 -->
		<u-toast ref="uToast" />
	</view>
</template>

<script>
import {
	mapGetters,
	mapActions
} from 'vuex'
import {
	reqLayeggs,
	reqWhipEggs,
	reqGetStatu,
	reqGetHouseId,
	reqLiuwo,
	reqDelInfo,
	reqDelStay
} from '@/api/index.js'
import {
	getNowDate
} from '@/getTime.js'
import {
	debounce
} from '@/utils/debounce.js'
export default {
	// props: ['houseId'],
	data() {
		return {
			tipList: [],
			num: [],
			baseFormData: {
				siteId: '',
				houseId: '',
				cageId: '',
				cageStatu: '预抽蛋',
				eggTime: ''
			},
			show: false,
			content: '确认操作吗？',
			// 判断用户是双击还是单击
			clickNum: '',
			lastTime: 0,
			msg: '',
			type: '',
			// 定时器
			timer: null,
			// 判断是长按还是单击
			islongPress: false,
			// 预抽蛋错误信息的id
			id: 0,
			// 留窝错误信息的id
			stayId: 0,
			eggId: 0,
			// 新增：前端操作记录管理
			frontendOperations: {},
			todayDate: '',
			isSubmitting: false,
			// 新增：操作历史记录
			operationHistory: {}
		}
	},
	mounted() {
		// 初始化前端操作记录
		this.initFrontendOperations();
		this.getStatu()
		this.getDate()
		
		// 保留事件监听，但主要依靠watch来响应变化
		uni.$on('siteChanged', (data) => {
			console.log('收到仓号变化事件，刷新数据', data);
			this.getStatu();
			this.getDate();
		});
		
		uni.$on('refreshCageStatus', (force) => {
			if (force) {
				console.log('收到强制刷新指令');
				this.getStatu();
				this.getDate();
			}
		});
	},
	
	// 在 beforeDestroy 中移除监听器
	beforeDestroy() {
		uni.$off('siteChanged');
		uni.$off('refreshCageStatus');
	},
	
	onPullDownRefresh() {
		this.getDate()
	},
	computed: {
	  ...mapGetters([
	    'nfcId', 
	    'show_nfcId', 
	    'cageStatu', 
	    'loading', 
	    'lastCageStatu', 
	    'whipCount', 
	    'stayCount',
	    'cageId', 
	    'layTime',
	    'operationSiteId'
	  ]),
	  
	  // 添加响应式计算属性
	  currentHouseInfo() {
	    return this.show_nfcId ? `鸽舍号：${this.show_nfcId}` : '鸽舍号';
	  },
	  
		// 获取今日日期字符串
		todayDateKey() {
			const now = new Date();
			return `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')}`;
		}
	},
	watch: {
	  // 监听 NFC ID 变化
	  nfcId: {
	    immediate: true,
	    handler(newVal) {
	      if (newVal) {
	        this.getStatu();
	        this.getDate();
	      }
	    }
	  },
	  
	  // 监听鸽舍号显示变化
	  show_nfcId(newVal) {
	    console.log('鸽舍号更新:', newVal);
	  }
	},
	methods: {
		// 初始化前端操作记录
		initFrontendOperations() {
			this.todayDate = this.todayDateKey;
			try {
				const stored = uni.getStorageSync('frontendOperations');
				if (stored && stored.date === this.todayDate) {
					this.frontendOperations = stored.operations || {};
				} else {
					this.frontendOperations = {};
					this.saveFrontendOperations();
				}
				
				// 初始化操作历史记录
				const historyStored = uni.getStorageSync('operationHistory');
				if (historyStored && historyStored.date === this.todayDate) {
					this.operationHistory = historyStored.history || {};
				} else {
					this.operationHistory = {};
					this.saveOperationHistory();
				}
			} catch (e) {
				console.error('加载前端操作记录失败:', e);
				this.frontendOperations = {};
				this.operationHistory = {};
			}
		},
		
		// 保存前端操作记录
		saveFrontendOperations() {
			try {
				uni.setStorageSync('frontendOperations', {
					date: this.todayDate,
					operations: this.frontendOperations
				});
			} catch (e) {
				console.error('保存前端操作记录失败:', e);
			}
		},
		
		// 保存操作历史记录
		saveOperationHistory() {
			try {
				uni.setStorageSync('operationHistory', {
					date: this.todayDate,
					history: this.operationHistory
				});
			} catch (e) {
				console.error('保存操作历史记录失败:', e);
			}
		},
		
		// 记录操作历史
		recordOperationHistory(cageId, operationType) {
		  if (!this.operationHistory[cageId]) {
		    this.operationHistory[cageId] = [];
		  }
		  this.operationHistory[cageId].push({
		    type: operationType,
		    timestamp: new Date().getTime(),
		    dateString: new Date().toLocaleString() // 新增：便于调试
		  });
		  this.saveOperationHistory();
		  
		  console.log(`记录操作历史: ${cageId}号鸽笼, ${operationType}, 时间: ${new Date().toLocaleString()}`);
		},
		
		// 删除操作历史记录
		removeOperationHistory(cageId, operationType) {
			if (this.operationHistory[cageId]) {
				// 删除最后一个指定类型的操作
				const operations = this.operationHistory[cageId];
				for (let i = operations.length - 1; i >= 0; i--) {
					if (operations[i].type === operationType) {
						operations.splice(i, 1);
						break;
					}
				}
				this.saveOperationHistory();
			}
		},
		
		// 获取操作历史序列
		getOperationHistory(cageId) {
			return this.operationHistory[cageId] || [];
		},
		
		// 检查今日是否已操作
		checkTodayOperation(cageId, operationType) {
			const cageOps = this.frontendOperations[cageId];
			if (!cageOps) return false;
			return cageOps[operationType] === true;
		},
		
		// 记录今日操作
		recordTodayOperation(cageId, operationType) {
			if (!this.frontendOperations[cageId]) {
				this.frontendOperations[cageId] = {};
			}
			this.frontendOperations[cageId][operationType] = true;
			this.saveFrontendOperations();
			
			// 同时记录操作历史
			this.recordOperationHistory(cageId, operationType);
		},
		
		// 删除今日操作记录
		removeTodayOperation(cageId, operationType) {
			if (this.frontendOperations[cageId]) {
				this.frontendOperations[cageId][operationType] = false;
				this.saveFrontendOperations();
			}
			
			// 同时删除操作历史记录
			this.removeOperationHistory(cageId, operationType);
		},
		
		// 抽蛋或留窝样式
		setStyle(str) {
			if (str === '抽蛋' || str === '留窝') {
				return true;
			} else return false;
		},
		// 获取查蛋页面中的时间
		async getDate() {
		  const obj = {
		    siteId: uni.getStorageSync('siteId'),
		    houseId: this.nfcId,
		    twoOrSix: 3
		  }
		  // 直接调用，不添加额外延迟
		  await this.$store.dispatch('getDate', obj);
		},

		formatting(dateStr) {
			return dateStr.substring(5, 10);
		},
		// 获取鸽笼状态
		async getStatu() {
		  const obj = {
		    siteId: uni.getStorageSync('siteId'),
		    houseId: this.nfcId,
		  }
		  // 立即获取状态
		  await this.$store.dispatch('getStatu', obj);
		  // 存储为上一次状态
		  this.$store.commit('SETLASTSTATU', [...this.cageStatu]);
		},
		// 进行查蛋
		async layEggs(cageId) {
			// 赋值给cageId
			this.baseFormData.siteId = uni.getStorageSync('siteId')
			this.baseFormData.houseId = this.nfcId
			this.baseFormData.cageId = cageId
			this.baseFormData.eggTime = getNowDate()
			this.$loading()
			await reqLayeggs(this.baseFormData).then((data) => {
				if (data.code == 200) {
					this.$refs.uToast.show({
						title: '查蛋成功',
						type: 'success',
						duration: '800',
						position: 'top'
					})
					this.id = data.id
					this.getStatu()
					this.getDate()
					this.getPR()
				} else {
					this.$refs.uToast.show({
						title: data.msg,
						type: 'warning',
						duration: '900',
						position: 'top'
					})
				}
			}).catch(() => {
				this.$refs.uToast.show({
					title: data.msg,
					type: 'error',
					duration: '900',
					position: 'top'
				})
			}).finally(() => {
				this.$hide()
			})
		},
		// 进行留窝
		async liuwo(cageId) {
			if (this.isSubmitting) return;
			
			// 检查今日是否已留窝
			if (this.checkTodayOperation(cageId, 'stay')) {
				// 先检查数据一致性
				const consistencyCheck = await this.checkDataConsistency(cageId, 'stay');
				if (consistencyCheck.consistent) {
					this.$refs.uToast.show({
						title: `${cageId}号鸽笼今日已留窝，请勿重复操作`,
						type: 'warning',
						duration: '1500',
						position: 'top'
					});
					return;
				} else {
					// 数据不一致，清除前端记录
					this.removeTodayOperation(cageId, 'stay');
					this.$refs.uToast.show({
						title: `${cageId}号鸽笼数据不一致，已自动修复`,
						type: 'success',
						duration: '1000',
						position: 'top'
					});
				}
			}
			
			this.isSubmitting = true;
			
			//置左侧面部仓号为抽蛋仓号
			this.$store.commit('SETOPESITEID',uni.getStorageSync('siteId'))
			this.$loading()
			const obj = {
				siteId: uni.getStorageSync('siteId'),
				houseId: this.nfcId,
				cageId,
				cageStatu: '留窝',
				stayTime: getNowDate()
			}
			
			try {
				let res = await reqLiuwo(obj)
				if (res.code === 200) {
					// 记录前端操作
					this.recordTodayOperation(cageId, 'stay');
					
					// 保存返回的ID
					this.stayId = res.stayId
					this.eggId = res.eggId
					
					// 强制刷新数据
					await Promise.all([
						this.getStatu(),
						this.getDate()
					]);
					
					this.getPR()
					this.stay()
					
					this.$refs.uToast.show({
						title: `${cageId}号鸽笼留窝成功`,
						type: 'success',
						duration: '800',
						position: 'top'
					})
				} else {
					// 后端操作失败，不记录前端操作
					this.$refs.uToast.show({
						title: res.msg,
						type: res.type,
						duration: '800',
						position: 'top'
					})
				}
			} catch (error) {
				console.error('留窝操作异常:', error);
				this.$refs.uToast.show({
					title: '留窝操作失败，请重试',
					type: 'error',
					duration: '800',
					position: 'top'
				})
			} finally {
				this.$hide()
				this.isSubmitting = false;
			}
		},
		// 进行抽蛋
		async whipEggs(cageId) {
			if (this.isSubmitting) return;
			
			// 检查今日是否已抽蛋
			if (this.checkTodayOperation(cageId, 'whip')) {
				// 先检查数据一致性
				const consistencyCheck = await this.checkDataConsistency(cageId, 'whip');
				if (consistencyCheck.consistent) {
					this.$refs.uToast.show({
						title: `${cageId}号鸽笼今日已抽蛋，请勿重复操作`,
						type: 'warning',
						duration: '1500',
						position: 'top'
					});
					return;
				} else {
					// 数据不一致，清除前端记录
					this.removeTodayOperation(cageId, 'whip');
					this.$refs.uToast.show({
						title: `${cageId}号鸽笼数据不一致，已自动修复`,
						type: 'success',
						duration: '1000',
						position: 'top'
					});
				}
			}
			
			this.isSubmitting = true;
			
			//置左侧面部仓号为抽蛋仓号
			this.$store.commit('SETOPESITEID',uni.getStorageSync('siteId'))
			const obj = {
				siteId: uni.getStorageSync('siteId'),
				houseId: this.nfcId,
				cageId,
				cageStatu: '抽蛋',
				whippingTime: getNowDate()
			}
			console.log(obj)
			
			try {
				let res = await reqWhipEggs(obj)
				// 请求成功则更新日期和状态
				if (res.code === 200) {
					// 记录前端操作
					this.recordTodayOperation(cageId, 'whip');
					
					this.getDate()
					this.getStatu()
					this.getPR()
					this.whip()
					
					this.$refs.uToast.show({
						title: `${cageId}号鸽笼抽蛋成功`,
						type: 'success',
						duration: '800',
						position: 'top'
					})
				} else {
					this.$refs.uToast.show({
						title: res.msg,
						type: res.type,
						duration: '800',
						position: 'top'
					})
				}
			} catch (error) {
				console.error('抽蛋操作异常:', error);
				this.$refs.uToast.show({
					title: '抽蛋操作失败，请重试',
					type: 'error',
					duration: '800',
					position: 'top'
				})
			} finally {
				this.isSubmitting = false;
			}
		},
		// 修改取消抽蛋操作
		async cancel(item) {
		  if (this.isSubmitting) return;
		  this.isSubmitting = true;
		  
		  // 检查是否为今天的数据
		  if (!this.checkIfTodayOperation(item.cage_id, 'whip')) {
		    this.$refs.uToast.show({
		      title: `${item.cage_id}号鸽笼的抽蛋操作不是今天的，无法删除`,
		      type: 'warning',
		      duration: '1500',
		      position: 'top'
		    })
		    this.isSubmitting = false;
		    return;
		  }
		  
		  // 新增：数据一致性检查
		  const consistencyCheck = await this.checkDataConsistency(item.cage_id, 'whip');
		  if (!consistencyCheck.consistent) {
		    this.$refs.uToast.show({
		      title: `${item.cage_id}号鸽笼数据不一致：${consistencyCheck.message}`,
		      type: 'warning',
		      duration: '2000',
		      position: 'top'
		    });
		    
		    // 自动修复：清除前端错误记录
		    if (consistencyCheck.shouldClean) {
		      await this.fixDataInconsistency(item.cage_id, 'whip');
		    }
		    
		    this.isSubmitting = false;
		    return;
		  }
		  
		  // 获取操作历史，检查最后一次操作是否是抽蛋
		  const history = this.getOperationHistory(item.cage_id);
		  const lastOperation = history[history.length - 1];
		  
		  if (!lastOperation || lastOperation.type !== 'whip') {
		    this.$refs.uToast.show({
		      title: `${item.cage_id}号鸽笼最后一次操作不是抽蛋，无法取消`,
		      type: 'warning',
		      duration: '800',
		      position: 'top'
		    })
		    this.isSubmitting = false;
		    return;
		  }
		  
		  // 置左侧面部仓号为抽蛋仓号
		  this.$store.commit('SETOPESITEID', uni.getStorageSync('siteId'))
		  
		  // 确定回退状态：删除抽蛋操作后，应该回到前一个状态
		  let rollbackStatus = '初始状态';
		  if (history.length > 1) {
		    const prevOperation = history[history.length - 2];
		    rollbackStatus = prevOperation.type === 'stay' ? '留窝' : 
		                    prevOperation.type === 'whip' ? '抽蛋' : '初始状态';
		  }
		  
		  console.log('回退状态:', rollbackStatus);
		  const obj = {
		    siteId: uni.getStorageSync('siteId'),
		    houseId: this.nfcId,
		    cageId: item.cage_id,
		    cageStatu: rollbackStatus,
		    id: this.id
		  }
		  console.log('取消抽蛋参数:', obj)
		  let res = await reqDelInfo(obj)
		  console.log('取消抽蛋结果:', res)
		  if (res.code === 200) {
		    // 删除前端操作记录中的最后一次抽蛋操作
		    this.removeTodayOperation(item.cage_id, 'whip');
		    
		    this.id = 0
		    
		    // 确保状态和日期更新完成后再获取比例
		    await Promise.all([
		      this.getStatu(),
		      this.getDate()
		    ]);
		    
		    // 强制重新获取比例
		    this.getPR();
		    
		    // 播放撤回音效
		    this.withdraw();
		            
		    this.$refs.uToast.show({
		      title: `${item.cage_id}号鸽笼抽蛋记录已删除`,
		      type: 'success',
		      duration: '800',
		      position: 'top'
		    })
		  } else {
		    this.$refs.uToast.show({
		      title: res.msg,
		      type: res.type,
		      duration: '800',
		      position: 'top'
		    })
		  }
		  this.isSubmitting = false;
		},

		
		// 修改取消留窝操作
		async cancelLiu(item) {
		  if (this.isSubmitting) return;
		  this.isSubmitting = true;
		  
		  // 检查是否为今天的数据
		  if (!this.checkIfTodayOperation(item.cage_id, 'stay')) {
		    this.$refs.uToast.show({
		      title: `${item.cage_id}号鸽笼的留窝操作不是今天的，无法删除`,
		      type: 'warning',
		      duration: '1500',
		      position: 'top'
		    })
		    this.isSubmitting = false;
		    return;
		  }
		  
		  // 新增：数据一致性检查
		  const consistencyCheck = await this.checkDataConsistency(item.cage_id, 'stay');
		  if (!consistencyCheck.consistent) {
		    this.$refs.uToast.show({
		      title: `${item.cage_id}号鸽笼数据不一致：${consistencyCheck.message}`,
		      type: 'warning',
		      duration: '2000',
		      position: 'top'
		    });
		    
		    // 自动修复：清除前端错误记录
		    if (consistencyCheck.shouldClean) {
		      await this.fixDataInconsistency(item.cage_id, 'stay');
		    }
		    
		    this.isSubmitting = false;
		    return;
		  }
		  
		  // 获取操作历史，检查最后一次操作是否是留窝
		  const history = this.getOperationHistory(item.cage_id);
		  const lastOperation = history[history.length - 1];
		  
		  if (!lastOperation || lastOperation.type !== 'stay') {
		    this.$refs.uToast.show({
		      title: `${item.cage_id}号鸽笼最后一次操作不是留窝，无法取消`,
		      type: 'warning',
		      duration: '800',
		      position: 'top'
		    })
		    this.isSubmitting = false;
		    return;
		  }
		  
		  // 置左侧面部仓号为抽蛋仓号
		  this.$store.commit('SETOPESITEID', uni.getStorageSync('siteId'))
		  
		  // 确定回退状态：删除留窝操作后，应该回到前一个状态
		  let rollbackStatus = '初始状态';
		  if (history.length > 1) {
		    const prevOperation = history[history.length - 2];
		    rollbackStatus = prevOperation.type === 'stay' ? '留窝' : 
		                    prevOperation.type === 'whip' ? '抽蛋' : '初始状态';
		  }
		  
		  console.log('回退状态:', rollbackStatus);
		  const obj = {
		    siteId: uni.getStorageSync('siteId'),
		    houseId: this.nfcId,
		    cageId: item.cage_id,
		    cageStatu: rollbackStatus,
		    eggId: this.eggId,
		    stayId: this.stayId
		  }
		  console.log('取消留窝参数:', obj)
		  let res = await reqDelStay(obj)
		  console.log('取消留窝结果:', res)
		  if (res.code === 200) {
		    // 删除前端操作记录中的最后一次留窝操作
		    this.removeTodayOperation(item.cage_id, 'stay');
		    
		    this.eggId = 0
		    this.stayId = 0
		    
		    // 确保状态和日期更新完成后再获取比例
		    await Promise.all([
		      this.getStatu(),
		      this.getDate()
		    ]);
		    
		    // 强制重新获取比例
		    this.getPR();
		    
		    // 播放撤回音效
		    this.withdraw();
		    
		    this.$refs.uToast.show({
		      title: `${item.cage_id}号鸽笼留窝记录已删除`,
		      type: 'success',
		      duration: '800',
		      position: 'top'
		    })
		  } else {
		    this.$refs.uToast.show({
		      title: res.msg,
		      type: res.type,
		      duration: '800',
		      position: 'top'
		    })
		  }
		  this.isSubmitting = false;
		},
		// 修改长按事件处理函数
		longPress(item) {
			console.log('长按事件')
			this.islongPress = true
			
			// 获取该鸽笼的操作历史记录
			const history = this.getOperationHistory(item.cage_id);
			console.log('操作历史:', history);
			
			if (history.length === 0) {
				// 提供数据修复选项
				uni.showActionSheet({
					itemList: ['数据修复'],
					success: async (res) => {
						if (res.tapIndex === 0) {
							await this.fixDataInconsistency(item.cage_id, 'all');
						}
					}
				});
				return;
			}
			
			// 获取最后一次操作
			const lastOperation = history[history.length - 1];
			console.log('最后一次操作:', lastOperation);
			
			if (lastOperation.type === 'whip') {
				this.cancel(item)
			} else if (lastOperation.type === 'stay') {
				this.cancelLiu(item)
			} else {
				this.$refs.uToast.show({
					title: `${item.cage_id}号鸽笼操作类型未知`,
					type: 'warning',
					duration: '800',
					position: 'top'
				})
			}
		},

		// 点击结束后将islongPress置为false，等待下一次操作
		tounchend() {
			setTimeout(() => {
				this.islongPress = false
			}, 200)
		},
		// 单击或双击鸽笼时
		async submit(item) {
			if (this.isSubmitting) return;
			
			this.cage_id = item.cage_id
			if (this.islongPress === false) {
				let _this = this
				let curTime = new Date().getTime()
				let lastTime = this.lastTime
				_this.lastTime = curTime
				let diff = curTime - lastTime;
				console.log('diff', diff)
				// 双击
				if (diff < 300) {
					clearTimeout(_this.timer)
					await this.liuwo(item.cage_id)
				} else {
					_this.timer = setTimeout(async () => {
						await this.whipEggs(item.cage_id)
					}, 300)
				}
			}
		},
		// 获取当天留窝抽蛋比例
		getPR() {
			if (uni.getStorageSync('siteId')) {
				// console.log('有site')
				const obj = {
					site_id: uni.getStorageSync('siteId')
				}
				this.$store.dispatch('getEWPR', obj)
			}
		},
		toExp() {
			uni.navigateTo({
				url: '/pages/expection/expection'
			})
		},
		
		//创建音频实例
		createAudio(audioSrc){
			this.innerAudioContext = uni.createInnerAudioContext(); //创建播放器对象
			this.innerAudioContext.src = audioSrc;//生成的mp3音频文件地址
			this.innerAudioContext.play();//执行播放
			this.innerAudioContext.onEnded(() => {
				//播放结束
				this.innerAudioContext.destroy();
				this.innerAudioContext = null;
			});
			this.innerAudioContext.onError((res) => {
				console.log(res.errMsg);
				console.log(res.errCode);
			})
		},
		
		//抽蛋音频播报
		whip(){
			this.createAudio('../../static/audio/whip.mp3');
		},
		//留窝音频播报
		stay(){
			this.createAudio('../../static/audio/stay.mp3');
		},
		// 撤回音频播报
		withdraw(){
			this.createAudio('../../static/audio/withdraw.mp3');
		},
		
		// 新增：检查是否为今天操作的方法（多重验证）
		checkIfTodayOperation(cageId, operationType) {
		  // 方法1：检查前端操作记录
		  if (this.checkTodayOperation(cageId, operationType)) {
		    return true;
		  }
		  
		  // 方法2：检查操作历史记录的时间戳
		  const history = this.getOperationHistory(cageId);
		  const lastOperation = history[history.length - 1];
		  if (lastOperation && lastOperation.type === operationType) {
		    const operationDate = new Date(lastOperation.timestamp);
		    const today = new Date();
		    const isToday = (
		      operationDate.getFullYear() === today.getFullYear() &&
		      operationDate.getMonth() === today.getMonth() &&
		      operationDate.getDate() === today.getDate()
		    );
		    
		    console.log(`操作时间检查: ${cageId}号鸽笼, 类型: ${operationType}, 是否为今天: ${isToday}`);
		    return isToday;
		  }
		  
		  // 方法3：如果以上都不行，尝试检查当前时间（最后的手段）
		  console.log(`无法确定 ${cageId}号鸽笼的 ${operationType} 操作时间，使用当前时间判断`);
		  return true; // 默认允许操作，避免因时间显示问题导致无法删除
		},
		
		// 新增：检查数据一致性
		async checkDataConsistency(cageId, operationType) {
		  try {
		    // 获取后端时间记录
		    const cageData = this.layTime.find(item => item.cage_id === cageId);
		    const timeRecords = cageData ? cageData.time : [];
		    
		    // 根据操作类型检查对应的后端记录
		    let expectedStatus = '';
		    if (operationType === 'stay') {
		      expectedStatus = 'line-bottom'; // 留窝
		    } else if (operationType === 'whip') {
		      expectedStatus = 'line-through'; // 抽蛋
		    }
		    
		    // 检查今天是否有对应的后端记录
		    const today = this.todayDateKey;
		    const hasBackendRecord = timeRecords.some(record => {
		      const recordDate = record.egg_time.substring(0, 10);
		      return recordDate === today && record.statu === expectedStatus;
		    });
		    
		    console.log(`数据一致性检查: ${cageId}号鸽笼, 操作: ${operationType}, 后端记录: ${hasBackendRecord}`);
		    
		    if (!hasBackendRecord) {
		      return {
		        consistent: false,
		        message: '后端无对应记录',
		        shouldClean: true
		      };
		    }
		    
		    return { consistent: true };
		  } catch (error) {
		    console.error('数据一致性检查失败:', error);
		    return {
		      consistent: false,
		      message: '检查过程中发生错误',
		      shouldClean: false
		    };
		  }
		},

		// 新增：数据修复方法
		async fixDataInconsistency(cageId, operationType) {
		  console.log(`开始修复 ${cageId} 号鸽笼的 ${operationType} 操作数据不一致问题`);
		  
		  if (operationType === 'all') {
		    // 清除所有前端错误记录
		    this.removeTodayOperation(cageId, 'stay');
		    this.removeTodayOperation(cageId, 'whip');
		  } else {
		    // 清除特定操作的前端错误记录
		    this.removeTodayOperation(cageId, operationType);
		  }
		  
		  // 强制刷新后端数据
		  await this.getStatu();
		  await this.getDate();
		  
		  this.$refs.uToast.show({
		    title: `${cageId}号鸽笼数据已修复`,
		    type: 'success',
		    duration: '1000',
		    position: 'top'
		  });
		}
	}
}
</script>

<style lang="scss" scoped>
	@import 'styles/builder.scss';

	.ycd {
		color: #dbe2f1;
		background-color: #89a5d6;
	}

	.other {
		color: #89a5d6;
		background-color: #dbe2f1;
	}

	.houseId {
		width: 100%;
		margin: 10rpx auto;
		padding: 18.12rpx 18.12rpx;
		font-size: 39.86rpx;
		color: #fff;
		background-color: #7d9ad2;
	}

	.control {
		width: 50%;
		margin: 0 auto;
		font-size: 39.86rpx;
		font-weight: 700;
		color: #2979ff;
		padding: 18.12rpx 18.12rpx;
	}

	.circle {
		width: 100%;

		h1 {
			text-align: center;
			font-weight: 700;
		}

		.ul {
			display: flex;
			flex-direction: row;
			flex-wrap: wrap;
			justify-content: space-between;
			width: 100%;
			padding: 20rpx;
			box-sizing: border-box;
			font-family: 'ExpectionNumber';

			.box {
				width: 48%; /* 一行两个，每个占48%宽度 */
				margin-bottom: 30rpx;
				display: flex;
				justify-content: center;
			}
			
			.li {
				display: flex;
				width: 100%;
				height: 150rpx;
				align-items: center;
				
				/* 奇数鸽笼：时间在左，鸽笼在右 */
				&:nth-child(odd) {
					justify-content: space-between;
					
					.time_list {
						width: 120rpx;
						height: 100%;
						display: flex;
						flex-direction: column;
						justify-content: space-around;
						align-items: flex-start;
						
						span {
							font-weight: normal;
							color: #a8a8a7;
							font-size: 18rpx;
							line-height: 1.2;
							padding: 2rpx 4rpx;
							border-radius: 4rpx;
							
							&.line-bottom {
								color: #4CAF50;
								font-weight: bold;
							}
							
							&.line-through {
								color: #FF9800;
								font-weight: bold;
							}
							
							&.breakage {
								color: #F44336;
								font-weight: bold;
							}
							
							&.out {
								color: #9E9E9E;
								text-decoration: line-through;
							}
						}
					}
					
					.cage_info {
						width: 125rpx;
						height: 130rpx;
						box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
						border-radius: 20rpx;
						display: flex;
						flex-direction: column;
						justify-content: center;
						align-items: center;
						transition: all 0.3s ease;
						
						&:active {
							transform: scale(0.95);
							opacity: 0.8;
						}
					}
				}
				
				/* 偶数鸽笼：鸽笼在左，时间在右 */
				&:nth-child(even) {
					justify-content: space-between;
					flex-direction: row-reverse;
					
					.time_list {
						width: 120rpx;
						height: 100%;
						display: flex;
						flex-direction: column;
						justify-content: space-around;
						align-items: flex-end;
						
						span {
							font-weight: normal;
							color: #a8a8a7;
							font-size: 18rpx;
							line-height: 1.2;
							padding: 2rpx 4rpx;
							border-radius: 4rpx;
							
							&.line-bottom {
								color: #4CAF50;
								font-weight: bold;
							}
							
							&.line-through {
								color: #FF9800;
								font-weight: bold;
							}
							
							&.breakage {
								color: #F44336;
								font-weight: bold;
							}
							
							&.out {
								color: #9E9E9E;
								text-decoration: line-through;
							}
						}
					}
					
					.cage_info {
						width: 125rpx;
						height: 130rpx;
						box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
						border-radius: 20rpx;
						display: flex;
						flex-direction: column;
						justify-content: center;
						align-items: center;
						transition: all 0.3s ease;
						
						&:active {
							transform: scale(0.95);
							opacity: 0.8;
						}
					}
				}

				.cage_info {
					.cage_number {
						font-size: 80rpx;
						font-weight: bold;
						line-height: 1;
					}

					.cage_statu {
						font-size: 20rpx;
						font-weight: 700;
						margin-top: 10rpx;
					}
				}
			}
		}

		.abnormal {
			@include flex(space-around, center, 'items') 
			width: 70%;
			height: 120rpx;
			margin: 0 auto;
			padding: 20rpx 57.97rpx;
			font-size: 38.04rpx;
			font-weight: 700;
			color: #fff;
			box-shadow: 9px 4px 10px 0 #7d9ad2;
			background-color: #7d9ad2;
		}
	}

	@keyframes scale {
		0% {
			transform: scale(1);
		}

		50% {
			transform: scale(0.75);
		}

		100% {
			transform: scale(1);
		}
	}
	
	/* 新增：数据修复提示样式 */
	.data-fix-tip {
		position: fixed;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		background-color: rgba(0, 0, 0, 0.8);
		color: white;
		padding: 20rpx 40rpx;
		border-radius: 10rpx;
		z-index: 9999;
		font-size: 28rpx;
	}
</style>